package com.reservation.mapper;

import com.reservation.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户数据访问接口
 */
@Mapper
@Repository
public interface UserMapper {

    /**
     * 根据ID查询用户
     */
    @Select("SELECT * FROM users WHERE id = #{id}")
    User selectById(Long id);

    /**
     * 根据用户名查询用户
     */
    @Select("SELECT * FROM users WHERE username = #{username}")
    User selectByUsername(String username);

    /**
     * 根据手机号查找用户
     */
    @Select("SELECT * FROM users WHERE phone = #{phone}")
    User selectByPhone(String phone);

    /**
     * 根据邮箱查找用户
     */
    @Select("SELECT * FROM users WHERE email = #{email}")
    User selectByEmail(String email);

    /**
     * 查询所有活跃用户
     */
    @Select("SELECT * FROM users WHERE is_active = true ORDER BY id ASC")
    List<User> selectAllActive();

    /**
     * 根据ID查找激活的用户
     */
    @Select("SELECT * FROM users WHERE id = #{id} AND is_active = true")
    User selectByIdAndActive(Long id);

    /**
     * 根据姓名模糊查询用户
     */
    @Select("SELECT * FROM users WHERE is_active = true AND LOWER(name) LIKE CONCAT('%', LOWER(#{name}), '%') ORDER BY id ASC")
    List<User> selectByNameLike(String name);

    /**
     * 插入用户
     */
    @Insert("INSERT INTO users(username, password, name, email, phone, address, is_active, created_at, updated_at) " +
           "VALUES(#{username}, #{password}, #{name}, #{email}, #{phone}, #{address}, #{isActive}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(User user);

    /**
     * 更新用户
     */
    @Update("UPDATE users SET username=#{username}, password=#{password}, " +
           "name=#{name}, email=#{email}, phone=#{phone}, address=#{address}, is_active=#{isActive}, updated_at=NOW() " +
           "WHERE id=#{id}")
    int update(User user);

    /**
     * 删除用户
     */
    @Delete("DELETE FROM users WHERE id=#{id}")
    int deleteById(Long id);
}
